import { useToken } from '@/stores/token';
import axios, { AxiosError, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus';
import router from '@/router';
import type { ResponseResult } from '@/types/common';

const service = axios.create({
  baseURL: '/tj',
  timeout: 5000,
})

service.interceptors.request.use(
  (config:InternalAxiosRequestConfig) => {
    const store = useToken();

    //注入token
    if(store.getToken()){
      config.headers.Authorization = store.getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use((response:AxiosResponse) => {
  const result = response.data
  if (result.code == 10000) {
    return response.data.data
  }
  ElMessage({
    message: result.msg,
    type: 'error',
  })
  return Promise.reject(new Error(result.msg))
}, (error:AxiosError) => {
  if(error.status == 401){
    const store = useToken()
    store.removeToken()
    router.push('/login')
  }else{
    const res = error.response?.data as ResponseResult
    ElMessage({
      message: res.msg,
      type: 'error',
    })
  }
  return Promise.reject(error)
})

export class Http {
  static get<T> (url:string  , params?: object) {
    return service.get<null , T>(url , { params })
  }

  static post<T> (url:string  , data?: object) {
    return service.post<null , T>(url , data)
  }

  static put<T> (url:string  , data?: object) {
    return service.put<null , T>(url , data)
  }

  static delete<T> (url:string  , params?: object) {
    return service.delete<null , T>(url , { params })
  }
}

export default service
